<template>
  <div class="dashboard-container">
    <!-- 顶部导航 -->
    <header class="dashboard-header">
      <div class="header-left">
        <h1 class="dashboard-logo">仪表板</h1>
      </div>
      <nav class="header-nav">
        <button @click="navigateTo('forum')">论坛</button>
        <button @click="navigateTo('studentTaskDashboard')">任务检索</button>
        <button @click="navigateTo('group')">已加入任务</button>
        <button @click="navigateTo('profile')">个人信息</button>
        <button @click="navigateTo('sparkiepath')">职业规划</button>>
      </nav>
      <button class="menu-toggle" @click="toggleMobileMenu">☰</button>
    </header>

    <!-- 移动端菜单 -->
    <div v-if="mobileMenuOpen" class="mobile-menu">
      <button @click="navigateTo('forum')">论坛</button>
      <button @click="navigateTo('studentTaskDashboard')">任务检索</button>
      <button @click="navigateTo('group')">已加入任务</button>
      <button @click="navigateTo('profile')">个人信息</button>
    </div>

    <!-- 主体内容 -->
    <main class="dashboard-main">
      <!-- 已加入任务视图 -->
      <div v-if="currentView === 'group'" class="group-view">
        <!-- 筛选表单 -->
        <div class="filters card">
          <div class="filter-item">
            <label for="isLeader">是否为组长</label>
            <select id="isLeader" v-model="filters.isLeader">
              <option value="">全部</option>
              <option value="组长">是</option>
              <option value="组员">否</option>
            </select>
          </div>
          <div class="filter-item">
            <label for="status">任务状态</label>
            <select id="status" v-model="filters.status">
              <option value="">全部</option>
              <option v-for="status in taskStatuses" :key="status" :value="status">{{ status }}</option>
            </select>
          </div>
        </div>
        <!-- 小组列表：已加入的任务 -->
        <div v-if="filteredTasks.length > 0" class="group-list">
          <div
            v-for="task in filteredTasks"
            :key="task.task_id"
            class="group-card card"
            @click="navigateToTaskDetails(task.id)"
          >
            <h3 class="group-name">{{ task.title }}</h3>
            <p class="group-course">课程名称：{{ task.course }}</p>
            <button class="detail-btn" @click.stop="navigateToTaskDetails(task.task_id)">查看详情</button>
          </div>
        </div>
        <div v-else>
          <p>没有加入任何任务。</p>
        </div>
      </div>

      <!-- 论坛视图 -->
      <div v-if="currentView === 'forum'" class="forum-view">
        <div class="forum-sidebar card">
          <button
            v-for="category in forumCategories"
            :key="category.key"
            :class="{ active: selectedForumCategory === category.key }"
            @click="selectForumCategory(category.key)"
          >
            {{ category.label }}
          </button>
          <!-- 发布帖子按钮 -->
          <button class="publish-btn" @click="showPublishDialog = true">发布内容</button>
        </div>
        <div class="forum-content card">
          <h2>{{ currentCategoryLabel }}</h2>
          <ul class="forum-list">
            <li
              v-for="post in forumPosts"
              :key="post.id"
              @click="openPostDetail(post.id)"
              class="forum-item"
            >
              <div class="post-header">
                <div class="user-info">
                  <div class="avatar">
                    <!-- 用户头像，如果没有则使用默认头像 -->
                    <img :src="post.author_avatar || 'https://via.placeholder.com/40'" alt="用户头像">
                  </div>
                  <div class="user-details">
                    <span class="username">{{ post.author_name || '匿名用户' }}</span>
                    <span class="post-time">{{ post.created_at ? formatDate(post.created_at) : '未知时间' }}</span>
                  </div>
                </div>
                <div class="post-category" :class="post.category">
                  {{ getCategoryLabel(post.category) }}
                </div>
              </div>
              <div class="post-content">
                <h3 class="post-title">{{ post.title }}</h3>
                <p class="post-summary">{{ post.summary }}</p>
              </div>
              <div class="post-footer">
                <div class="post-stats">
                  <span class="views"><i class="fas fa-eye"></i> {{ post.views || 0 }}</span>
                  <span class="comments"><i class="fas fa-comment"></i> {{ post.comments_count || 0 }}</span>
                  <span class="likes"><i class="fas fa-heart"></i> {{ post.likes || 0 }}</span>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>

      <!-- 发布帖子弹窗 -->
      <div v-if="showPublishDialog" class="dialog-overlay">
        <div class="dialog-content card">
          <h2>发布新帖子</h2>
          <form @submit.prevent="createForumPost">
            <div>
              <label>标题：</label>
              <input type="text" v-model="newPost.title" required />
            </div>
            <div>
              <label>内容：</label>
              <textarea v-model="newPost.content" required></textarea>
            </div>
            <div>
              <label>上传附件：</label>
              <input type="file" @change="handleAttachmentUpload" />
            </div>
            <div>
              <label>选择分类：</label>
              <select v-model="newPost.category">
                <option v-for="category in forumCategories" :key="category.key" :value="category.key">
                  {{ category.label }}
                </option>
              </select>
            </div>
            <div class="dialog-actions">
              <button type="submit">发布</button>
              <button type="button" @click="showPublishDialog = false">取消</button>
            </div>
          </form>
        </div>
      </div>

      <!-- 班级任务视图 -->
      <div v-if="currentView === 'studentTaskDashboard'" class="task-dashboard-view">
        <StudentTaskDashBoard />
      </div>
      <div v-if="currentView === 'sparkiepath'" class="sparkiepath-view">
        <!-- 直接渲染 SparkiePath 组件 -->
        <SparkiePath />
      </div>
      <!-- 个人信息视图 -->
      <div class="profile-view card" v-if="currentView === 'profile'">
        <h2>个人信息</h2>
        <div v-if="userProfile">
          <p>ID：{{ userProfile.user_id }}</p>
          <p>用户名：{{ userProfile.username }}</p>
          <p>邮箱：{{ userProfile.email }}</p>
        </div>
        <div v-else>
          <p>加载中...</p>
        </div>
        <!-- 雷达图展示用户能力维度 -->
        <div class="chart-container">
          <canvas id="profileRadarChart"></canvas>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="dashboard-footer">
      <p>© 2025 SparkieLink. 版权所有.</p>
    </footer>
  </div>
</template>

<script>
import axios from '@/axiosInstance';
import SparkiePath from '@/components/sparkiepath.vue'
import StudentTaskDashBoard from "./StudentTaskDashBoard.vue";
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

export default {
  components: {
    StudentTaskDashBoard,
    SparkiePath,
  },
  data() {
    return {
      currentView: "group",
      mobileMenuOpen: false,
      // 论坛分类设置：与后端 model 保持一致
      forumCategories: [
        { key: 'publish', label: '发布内容' },
        { key: 'recruitment', label: '企业招募' },
        { key: 'experience', label: '经验分享' },
        { key: 'research', label: '课题研究' },
        { key: 'teamup', label: '竞赛组队' }
      ],
      selectedForumCategory: 'publish',
      forumPosts: [],
      showPublishDialog: false,
      newPost: {
        title: '',
        content: '',
        category: 'publish',
        // 统一附件字段为 attachment
        attachment: null
      },
      filters: {
        isLeader: "",
        status: ""
      },
      groups: [],
      userProfile: null,
      radarChart: null,
      taskStatuses: ["进行中", "已完成"]
    };
  },
  computed: {
    filteredTasks() {
      console.log("当前过滤的任务数据：", this.groups);
      return this.groups.filter(task => {
        console.log("任务数据:", task);
        return (
          (this.filters.isLeader === "" || task.position === this.filters.isLeader) &&
          (this.filters.status === "" || task.status === this.filters.status)
        );
      });
    },
    currentCategoryLabel() {
      const cat = this.forumCategories.find(item => item.key === this.selectedForumCategory);
      return cat ? cat.label : '';
    }
  },
  methods: {
    async navigateTo(view) {
      this.currentView = view;
      this.mobileMenuOpen = false;
      if (view === "profile") {
        await this.fetchUserProfile();
      } else if (view === 'forum') {
        this.fetchForumPosts();
      }
    },
    
    // 格式化日期显示
    formatDate(dateString) {
      if (!dateString) return '未知时间';
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return '无效日期';
      
      const now = new Date();
      const diffMs = now - date;
      const diffSec = Math.floor(diffMs / 1000);
      const diffMin = Math.floor(diffSec / 60);
      const diffHour = Math.floor(diffMin / 60);
      const diffDay = Math.floor(diffHour / 24);
      
      if (diffDay > 30) {
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
      } else if (diffDay > 0) {
        return `${diffDay}天前`;
      } else if (diffHour > 0) {
        return `${diffHour}小时前`;
      } else if (diffMin > 0) {
        return `${diffMin}分钟前`;
      } else {
        return '刚刚';
      }
    },
    
    // 获取分类标签
    getCategoryLabel(categoryKey) {
      const category = this.forumCategories.find(c => c.key === categoryKey);
      return category ? category.label : '未分类';
    },
    toggleMobileMenu() {
      this.mobileMenuOpen = !this.mobileMenuOpen;
      console.log("toggleMobileMenu triggered, mobileMenuOpen:", this.mobileMenuOpen);
    },
    selectForumCategory(categoryKey) {
      console.log("selectForumCategory triggered, categoryKey:", categoryKey);
      this.selectedForumCategory = categoryKey;
      this.fetchForumPosts();
    },
    async fetchForumPosts() {
      try {
        const response = await axios.get('http://39.105.217.183:8000/api/forum-posts/', {
          params: { category: this.selectedForumCategory }
        });
        if (response.data && Array.isArray(response.data.posts)) {
          this.forumPosts = response.data.posts;
        } else {
          console.error("获取帖子列表失败");
        }
      } catch (error) {
        console.error("获取论坛帖子错误:", error.message || error);
      }
    },
    openPostDetail(postId) {
      this.$router.push({ name: 'forum-post-detail', params: { post_id: postId } });
    },
    // 统一上传附件方法
    handleAttachmentUpload(event) {
      const file = event.target.files[0];
      this.newPost.attachment = file;
      console.log("handleAttachmentUpload triggered:", file);
    },
    async createForumPost() {
      try {
        const formData = new FormData();
        formData.append("title", this.newPost.title);
        formData.append("content", this.newPost.content);
        formData.append("category", this.newPost.category);
        // 附件字段使用 attachment
        if (this.newPost.attachment) {
          formData.append("attachment", this.newPost.attachment);
        }
        // 前端传递 author_id（假设已登录）
        formData.append("author_id", this.$store.state.user.user_id);
        const response = await axios.post(
          'http://39.105.217.183:8000/api/create-forum-post/',
          formData,
          { headers: { "Content-Type": "multipart/form-data" } }
        );
        console.log("发布返回结果：", response.data);
        if (response.data && response.data.post && response.data.post.id) {
          this.showPublishDialog = false;
          this.fetchForumPosts();
          this.newPost = { title: '', content: '', category: 'publish', attachment: null };
        } else {
          console.error("发布帖子失败：", response.data.message || response.data);
        }
      } catch (error) {
        console.error("创建帖子错误：", error.response ? error.response.data : error.message);
      }
    },
    async fetchUserProfile() {
      try {
        const user = this.$store.state.user || JSON.parse(localStorage.getItem("user"));
        if (!user || !user.user_id) {
          alert("用户未登录或用户信息缺失");
          this.$router.push("/login");
          return;
        }
        const response = await axios.get("http://39.105.217.183:8000/api/user/profile/", {
          params: {user_id: user.user_id}
        });
        console.log("后端返回的数据：", response.data);
        if (response.data && response.data.user_id) {
          this.userProfile = response.data;
          console.log("获取的用户信息：", this.userProfile);
          await this.$nextTick(() => {
            this.renderRadarChart();
          });
        } else {
          console.error("获取个人信息失败:", response.data.message);
        }
      } catch (error) {
        console.error("获取个人信息错误:", error.message || error);
      }
    },
    async navigateToTaskDetails(taskId) {
      try {
        console.log("获取的任务ID:", taskId);
        const user = this.$store.state.user || JSON.parse(localStorage.getItem("user"));
        const sysUserId = user.user_id;
        this.$router.push({
          path: '/leader-dashboard',
          query: {taskId: taskId, sysUserId: sysUserId}
        });
      } catch (error) {
        console.error("跳转到任务详情页面失败:", error.message || error);
      }
    },
    async fetchJoinedTasks() {
      try {
        const user = this.$store.state.user || JSON.parse(localStorage.getItem("user"));
        if (!user || !user.user_id) {
          alert("用户未登录或用户信息缺失");
          this.$router.push("/login");
          return;
        }
        const response = await axios.get("http://39.105.217.183:8000/api/user/joined-tasks/", {
          params: {user_id: user.user_id}
        });
        console.log("已加入任务数据:", response.data);
        if (response.data && Array.isArray(response.data)) {
          this.groups = response.data;
        } else {
          console.error("未能加载任务数据");
        }
      } catch (error) {
        console.error("获取任务错误:", error.message || error);
      }
    },
    renderRadarChart() {
      const ctx = document.getElementById("profileRadarChart");
      if (!ctx || !this.userProfile) return;
      const data = {
        labels: ["能力值", "参与积极性", "表达能力", "人气值", "信用值", "已完成任务次数"],
        datasets: [
          {
            label: "用户维度",
            data: [
              this.userProfile.ability || 60,
              this.userProfile.enthusiasm || 60,
              this.userProfile.communication || 60,
              this.userProfile.popularity || 60,
              this.userProfile.credit || 100,
              this.userProfile.times || 0
            ],
            backgroundColor: "rgba(37, 99, 235, 0.2)",
            borderColor: "rgba(37, 99, 235, 1)",
            borderWidth: 2,
            pointBackgroundColor: "rgba(37, 99, 235, 1)"
          }
        ]
      };
      if (this.radarChart) {
        this.radarChart.destroy();
      }
      this.radarChart = new Chart(ctx, {
        type: "radar",
        data: data,
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            r: {
              beginAtZero: true,
              max: 100
            }
          }
        }
      });
    }
  },
  mounted() {
    this.fetchUserProfile();
    this.fetchJoinedTasks();
  }
};
</script>

<style scoped>
/* 基础重置及字体 */
* {
  box-sizing: border-box;
}

@keyframes gradientAnimation {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

body {
  height: 100%;
  width: 70vw;
  max-width: 100%;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
  font-family: "Inter", sans-serif;
  background: linear-gradient(270deg, #2563eb, #a5b4fc, #4f46e5);
  background-size: 400% 400%;
  animation: gradientAnimation 10s ease infinite;
}

/* 整体仪表板容器 */
.dashboard-container {
  display: flex;
  max-width: 100%;
  width: 40vw;
  flex-direction: column;
  min-height: 100vh;
  align-items: stretch;
}

/* 顶部导航 */
.dashboard-header {
  background-color: #fff;
  border-bottom: 1px solid #e5e5e5;
  padding: 12px 20px;
  display: flex;
  align-items: stretch;
  justify-content: space-between;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
  width: 93%;
}

.header-left {
  display: flex;
  align-items: center;
}

.dashboard-logo {
  font-size: 2rem;
  color: #2563eb;
  margin: 0;
}

.header-nav {
  display: flex;
  gap: 20px;
}

.header-nav button {
  background-color: transparent;
  border: none;
  color: #333;
  font-size: 1rem;
  padding: 8px 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s ease-in-out, color 0.3s ease-in-out;
}

.header-nav button:hover {
  background-color: #e5e7eb;
  color: #2563eb;
}

.menu-toggle {
  display: none;
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #333;
}

/* 移动端菜单 */
.mobile-menu {
  display: none;
  width: 100%;
  flex-direction: column;
  background-color: #fff;
  border-bottom: 1px solid #e5e5e5;
}

.mobile-menu button {
  padding: 12px 20px;
  border: none;
  background: none;
  text-align: left;
  font-size: 1rem;
  color: #333;
  cursor: pointer;
  border-top: 1px solid #e5e5e5;
  transition: background-color 0.3s ease-in-out;
}

.mobile-menu button:hover {
  background-color: #f0f0f0;
}

/* 主体内容 */
.dashboard-main {
  flex: 1;
  padding: 20px;
  background-color: #f5f7fa;
  width: 90%;
  max-width: 100%;
  margin: 0 auto;
}

/* 通用卡片样式 */
.card {
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
  margin-bottom: 20px;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

/* 小组视图 */
.group-view .filters {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.filters .filter-item {
  flex: 1;
  min-width: 220px;
  display: flex;
  flex-direction: column;
}

.filters label {
  font-size: 14px;
  margin-bottom: 8px;
  color: #333;
}

.filters select {
  padding: 10px;
  font-size: 1rem;
  border: 1px solid #ccc;
  border-radius: 8px;
  outline: none;
  transition: border-color 0.3s ease-in-out;
}

.filters select:focus {
  border-color: #2563eb;
}

/* 小组列表：使用网格布局 */
.group-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.group-card {
  cursor: pointer;
  text-align: center;
  transition: transform 0.3s, box-shadow 0.3s;
}

.group-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.group-card .group-name {
  margin: 0;
  font-size: 1.6rem;
  color: #2563eb;
  font-weight: bold;
}

.group-card p {
  font-size: 1rem;
  margin: 8px 0;
  color: #555;
}

.detail-btn {
  background-color: #007bff;
  color: #fff;
  border: none;
  padding: 8px 16px;
  margin-top: 10px;
  cursor: pointer;
  border-radius: 5px;
  transition: background-color 0.3s;
  font-size: 1rem;
}

.detail-btn:hover {
  background-color: #0056b3;
}

/* 论坛视图 */
.forum-view {
  display: grid;
  grid-template-columns: 200px 1fr;
  gap: 20px;
}

.forum-sidebar {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 20px;
}

.forum-sidebar button {
  background-color: #28a745;
  color: #fff;
  border: none;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.forum-sidebar button:hover,
.forum-sidebar button.active {
  background-color: #1e7e34;
}

.publish-btn {
  margin-top: 20px;
  background-color: #007bff;
}

.forum-content h2 {
  margin-top: 0;
  color: #2563eb;
}

.forum-list {
  list-style: none;
  padding-left: 0;
}

.forum-item {
  padding: 16px;
  border-bottom: 1px solid #e5e5e5;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px;
  margin-bottom: 12px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.forum-item:hover {
  background-color: #f8f9fa;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 12px;
  border: 2px solid #e0e7ff;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 600;
  color: #3b82f6;
  font-size: 0.95rem;
}

.post-time {
  font-size: 0.8rem;
  color: #6b7280;
}

.post-category {
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 500;
  color: white;
  background-color: #4f46e5;
}

.post-category.recruitment {
  background-color: #0891b2;
}

.post-category.experience {
  background-color: #16a34a;
}

.post-category.research {
  background-color: #9333ea;
}

.post-category.teamup {
  background-color: #f59e0b;
}

.post-content {
  margin-bottom: 12px;
}

.post-title {
  font-size: 1.1rem;
  font-weight: 600;
  margin-bottom: 8px;
  color: #1e293b;
}

.post-summary {
  color: #4b5563;
  font-size: 0.95rem;
  line-height: 1.5;
}

.post-footer {
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f0f0;
  padding-top: 10px;
  margin-top: 10px;
}

.post-stats {
  display: flex;
  gap: 16px;
}

.post-stats span {
  display: flex;
  align-items: center;
  color: #6b7280;
  font-size: 0.85rem;
}

.post-stats i {
  margin-right: 5px;
  font-size: 0.9rem;
}

/* 弹窗 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.dialog-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  width: 80%;
  max-width: 600px;
}

.dialog-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 学生任务与个人信息视图 */
.task-dashboard-view,
.profile-view {
  max-width: 1000px;
  margin: 0 auto;
}

.profile-view p {
  font-size: 1.2rem;
  margin: 12px 0;
  color: #333;
}

.chart-container {
  position: relative;
  width: 100%;
  height: 300px;
  margin-top: 30px;
}

/* 页脚 */
.dashboard-footer {
  background-color: #003366;
  color: #fff;
  text-align: center;
  padding: 20px;
  font-size: 1rem;
  font-weight: 500;
}

/* 响应式设置 */
@media (max-width: 768px) {
  .header-nav {
    display: none;
  }

  .menu-toggle {
    display: block;
  }

  .mobile-menu {
    display: flex;
  }

  .forum-view {
    grid-template-columns: 1fr;
  }

  .filters .filter-item {
    flex: 1 1 100%;
  }

  .filters select {
    width: 100%;
  }
}

.sparkiepath-view {
  width: 100%;
  height: 100%;
}
</style>